﻿<%@ WebHandler Language="C#" Class="invoice" %>

using System;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;

public class invoice : IHttpHandler {
	
	Common Init=new Common();
	MsSqlHelper mssql = new MsSqlHelper();
    public string content;
    public string ids;
	public string djbh;
	public string bg;
	public string pj;
	public string fp;
	public string shd;
	public string sm;
	public string ent="";
    
    public void ProcessRequest (HttpContext context) {
        djbh = HttpContext.Current.Request.Params["djbh"];
		bg = HttpContext.Current.Request.Params["bg"];
		pj = HttpContext.Current.Request.Params["pj"];
		fp = HttpContext.Current.Request.Params["fp"];
		shd = HttpContext.Current.Request.Params["shd"];
		sm = HttpContext.Current.Request.Params["sm"];
		ent = HttpContext.Current.Request.Params["ent"];
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World"+djbh);		
		ZipFileByCodex(djbh);
    }	
	
	public DataTable DataR(string djbh){
		string sql="";
			if(shd=="true"){
                sql += "select rtrim(c.type_id) as type_id,'厂家随货同行单' as leibie,rtrim(a.spid) as spid,rtrim(a.pihao) as pihao,rtrim(c.imageid) as imageid,"
				  +" rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,rtrim(b.pizhwh) as pizhwh,c.url,rtrim(c.extend) as extend"
				  +" from [spls_ck] a(nolock)"
				  +" left join [ImageDoc] c(nolock) on a.rkdjbh=c.detailid and type_id='sh'"	  
				  +" ,spkfk b(nolock) where a.spid=b.spid"
				  +" and a.djbh='"+djbh+"'";
				if(!string.IsNullOrEmpty(ent)){	  
				  sql+=" and a.dwbh in(select dwbh from mchk(nolock) where dwmch='"+ent+"')";
				}				  
			}
			 if(fp=="true"){
				if(!string.IsNullOrEmpty(sql)){  
				  sql+=" union ";
				}
                sql += " select rtrim(c.type_id) as type_id,'厂家发票' as leibie,rtrim(a.spid) as spid,rtrim(a.pihao) as pihao,rtrim(c.imageid) as imageid,"
				  +" rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,rtrim(b.pizhwh) as pizhwh,c.url,rtrim(c.extend) as extend"
				  +" from spls_ck a(nolock)"
				  +" left join [ImageDoc] c(nolock) on a.rkdjbh=c.detailid and type_id='fa'"
				  +" ,spkfk b(nolock) where a.spid=b.spid"
                  +" and a.djbh='"+djbh+"'";
				  if(!string.IsNullOrEmpty(ent)){	  
				  sql+=" and a.dwbh in(select dwbh from mchk(nolock) where dwmch='"+ent+"')";
				}
			 }	  
			if(bg=="true"){
				if(!string.IsNullOrEmpty(sql)){  
				  sql+=" union ";
				}
                sql += " select rtrim(c.type_id) as type_id,'检验报告' as leibie,rtrim(a.spid) as spid,rtrim(a.pihao) as pihao,rtrim(c.imageid) as imageid,"
				  +" rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,rtrim(b.pizhwh) as pizhwh,c.url,rtrim(c.extend) as extend"
				  +" from spls_ck a(nolock)"
				  +" left join [ImageDoc] c(nolock) on a.spid=c.detailid and a.pihao=c.fzxx1 and type_id='bg'"
				  +" ,spkfk b(nolock) where a.spid=b.spid"
				  +" and a.djbh='"+djbh+"'";
				  if(!string.IsNullOrEmpty(ent)){	  
				  sql+=" and a.dwbh in(select dwbh from mchk(nolock) where dwmch='"+ent+"')";
				}
			}	  
			if(pj=="true"){
				if(!string.IsNullOrEmpty(sql)){  
				  sql+=" union ";
				}
                sql += " select rtrim(c.type_id) as type_id,'注册批件' as leibie,rtrim(a.spid) as spid,rtrim(a.pihao) as pihao,rtrim(c.imageid) as imageid,"
                + " rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,"
                + "rtrim(b.pizhwh) as pizhwh,c.url,rtrim(c.extend) as extend";
                if (djbh.StartsWith("XSA"))
                {
                    sql += " from spls_ck a(nolock)";
                }else{
                    sql += " from [192.168.0.4].ksoa.dbo.[pf_djmx] a ";
                }                
				 sql +=" left join [ImageDoc] c(nolock) on a.spid=c.detailid and type_id='pj'"
				  +" ,spkfk b(nolock) where a.spid=b.spid"
				  +" and a.djbh='"+djbh+"'";
				  if(!string.IsNullOrEmpty(ent)){	  
				  sql+=" and a.dwbh in(select dwbh from mchk(nolock) where dwmch='"+ent+"')";
				}
			}
			if(sm=="true"){
				if(!string.IsNullOrEmpty(sql)){  
				  sql+=" union ";
				}
                sql += " select rtrim(c.type_id) as type_id,'说明书' as leibie,rtrim(a.spid) as spid,rtrim(a.pihao) as pihao,rtrim(c.imageid) as imageid,"
				  +" rtrim(b.spbh) as spbh,rtrim(b.spmch) as spmch,rtrim(b.shpgg) as shpgg,rtrim(b.dw) as dw,rtrim(b.shengccj) as shengccj,rtrim(b.pizhwh) as pizhwh,c.url,rtrim(c.extend) as extend"
				  +" from spls_ck a(nolock)"
				  +" left join [ImageDoc] c(nolock) on a.spid=c.detailid and type_id='sm'"
				  +" ,spkfk b(nolock) where a.spid=b.spid"
				  +" and a.djbh='"+djbh+"'";
				  if(!string.IsNullOrEmpty(ent)){	  
				  sql+=" and a.dwbh in(select dwbh from mchk(nolock) where dwmch='"+ent+"')";
				}
			}
				  sql+=" order by leibie,spid desc";
		DataTable dt = mssql.ExecuteDt(sql);	
		return dt;
	}
    /// <summary>
    /// 压缩打包文件
    /// </summary>
    /// <param name="djbh">单据编号</param>
    public void ZipFileByCodex(string djbh)
    {
        if (djbh.Length != 0)
        {
            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;

            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。
				content+= "\r\n\r\n";
                content += "      " + Init.EntName + "\r\n";
				content+= "====================================\r\n";
				content+= "单据编号："+djbh+"\r\n";
				content+= "====================================\r\n";
				content+= "本出库单以下商品暂时没有商品信息：\r\n";
				content+= "(格式：序号.类别_商品名称_批号)\r\n";
				content+= "====================================\r\n";
				int fcount=0;		
				DataTable dt=DataR(djbh);
               for (int n = 0; n < dt.Rows.Count; n++)
               {
                   ids += dt.Rows[n]["imageid"].ToString() + ",";
				   string oldfilename = "H:\\" + dt.Rows[n]["url"].ToString().Replace("Upload", "TuPian");				   
				   string newfilename= (n+1).ToString().PadLeft(4,'0') +"."+dt.Rows[n]["leibie"].ToString() + "_" +dt.Rows[n]["spmch"].ToString() + "_" +  dt.Rows[n]["pihao"].ToString() + dt.Rows[n]["extend"].ToString();				   
				   string waterfilename="D:\\" + dt.Rows[n]["url"].ToString().Replace("Upload", "TuPian");
				   if(!string.IsNullOrEmpty(dt.Rows[n]["imageid"].ToString())){
                        if (File.Exists(oldfilename))
                        {
							if(!File.Exists(waterfilename)){
								bool flag=dt.Rows[n]["type_id"].ToString()=="bg"?true:false;								
								AddWatermarkAndSave(oldfilename,dt.Rows[n]["imageid"].ToString(),waterfilename,flag);
                            }                            							
							fcount++;
                            //file.Add(oldfilename,newfilename);  							
							file.Add(waterfilename,newfilename);
                        }
                        else
                        {
                            content += newfilename + "(图片丢失)\r\n";  
                        }
                        if (File.Exists(Init.imagefilepath(dt.Rows[n]["url"].ToString())))
                        {
                            file.Add(Init.imagefilepath(dt.Rows[n]["url"].ToString()), newfilename);
                        }
				   }else{
					  content+= newfilename+"\r\n";					   
				   }
                }
				if(fcount==0){
					file.Add(HttpRuntime.AppDomainAppPath+"\\Public\\nopic.jpg","没有找到资料.jpg");
				}				
				content += "====================================\r\n";
				content+="\r\n质量管理部 联系方式：\r\n    联系电话：028-83420470\r\n    质量反馈QQ：2850897874\r\n    检验报告接收QQ：2850897881\r\n    检验报告查找QQ：2850519828\r\n\r\n图片资料打包\r\nCopyright © 2018 Sitaier QQ:613329777 All rights reserved\r\n\r\n\r\n";
                content += ids;
				file.SetComment(content);
                file.CommitUpdate();
                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
            DateTime dtime = DateTime.Now;
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=文档系统" + dtime.ToLocalTime().ToString() + ".zip");
            System.Web.HttpContext.Current.Response.BinaryWrite(buffer);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }
    }	
	
	public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
    {
        #region INameTransform 成员
        public string TransformDirectory(string name)
        {
            return null;
        }

        public string TransformFile(string name)
        {
            return Path.GetFileName(name);
        }
        #endregion
    }
	
	/// <summary>
	/// 
	/// </summary>
	/// <param name="path">路径</param>
	/// <param name="fileName">文件名</param>
	/// <param name="newpath">新路径</param>
	/// <param name="flag">标识</param>
	/// <returns></returns>
    private bool AddWatermarkAndSave(string path, string fileName,string newpath,bool flag)
    {
        try
        {			
			DirectoryInfo info = new DirectoryInfo(newpath);
            string ePath = info.Parent.FullName;
            if (!Directory.Exists(ePath))
            {
                Directory.CreateDirectory(ePath);
            }
			System.Drawing.Image img = System.Drawing.Image.FromFile(path);
            int imgheight = img.Height;
            int imgwidth = img.Width;
            if (img.Height > 1754 && img.Width<img.Height)
            {
                imgheight = 1754;
                imgwidth =(int)((double)img.Width / ((double)img.Height / 1754.00));
            }
            if (img.Width > img.Height && img.Width > 1754)
            {
                imgwidth = 1754;
                imgheight = (int)((double)img.Height / ((double)img.Width / 1754.00));
            }
            if (img.Width > img.Height && img.Width < 1754)
            {
                imgwidth = 1754;
                imgheight = (int)((double)img.Height / ((double)img.Width / 1754.00));
            }
            if (img.Width < img.Height && img.Height < 1754)
            {
                imgheight = 1754;
                imgwidth = (int)((double)img.Width / ((double)img.Height / 1754.00)); 
            }
            if (img.Width == img.Height)
            {
                imgheight = 1240;
                imgwidth = 1240;
            }
			
            Bitmap Cover = new Bitmap(img, imgwidth, imgheight);
            //加载水印文件
            string basePath =(flag)? "~/Public/sitamp21.png": "~/Public/sitamp.png";
			string fullbasePath=(basePath.IndexOf("~") > -1) ? HttpContext.Current.Server.MapPath(basePath) : basePath;
            System.Drawing.Image water = System.Drawing.Image.FromFile(fullbasePath);
            Bitmap waters = new Bitmap(water, 300, 300);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(Cover);          
            g.DrawImage(waters, new Rectangle(Cover.Width - waters.Width - 80, 120, waters.Width, waters.Height), 0, 0, waters.Width, waters.Height, GraphicsUnit.Pixel);
            g.Dispose();
            Cover.Save(newpath , ImageFormat.Jpeg);								
            Cover.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            Init.WriteLog(ex.ToString(), true);
            return false;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}